<?php
/**
 * Created by PhpStorm.
 * User: HLG
 * Date: 2019/10/14
 * Time: 16:58
 */
namespace app\api\model;
use think\Model;

class BaseModel extends Model
{
    /*
     * 将对象转化成数组
     * */
    public function objToArray($obj)
    {
        return json_decode(json_encode($obj),true);
    }

    /**
     * 查询数据
     *
     * @param array $where
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getInfo($where = [], $field = '*')
    {
        $data = $this->field($field)->where($where)->find();
        return $data;
    }

    /**
     * 查询所有数据
     *
     * @param array $where
     * @param int $page
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList($where = [], $field = '*')
    {
        $list = $this->field($field)->where($where)->select();
        return $list;
    }
    /**
     * 修改数据
     *
     * @param array $where
     * @param array $data
     * @return bool
     */
    public function updateInfo($where = [], $data = [])
    {
        $result = $this->allowField(true)->isUpdate(true)->save($data,$where);
        if($result!==false){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 添加数据
     *
     * @param array $data
     * @return bool
     */
    public function insertInfo($data=[])
    {
        $result = $this->allowField(true)->isUpdate(false)->save($data);
        if($result){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 修改数据数量
     *
     * @param array $where
     * @param $sign 1增加
     * @param $field
     * @param $number
     * @return bool
     * @throws \think\Exception
     */
    public function updateNumber($where = [],$sign,$field,$number)
    {
        if($sign==1){ //增加
            $result = $this->where($where)->setInc($field,$number);
        }else{ //减少
            $result = $this->where($where)->setDec($field,$number);
        }
        if($result!==false){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 分页数据
     *
     * @param array $where
     * @param string $field
     * @param $page
     * @param $listNum
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPageList($where = [],$field = '*',$page,$listNum)
    {
        $list = $this->field($field)->where($where)->page($page,$listNum)->select();
        return $list;
    }
}